//
//  XJ_AccountBookViewController.m
//  XunJieProject
//
//  Created by xue on 2018/6/7.
//  Copyright © 2018年 Soowin. All rights reserved.
//

#import "XJ_AccountBookViewController.h"
#import "XJ_AccountBookListCell.h"
#import "XJ_AccountBook_DetailViewController.h"
#import "ZDXAdditionalView.h"
#import "XJ_DealListModel.h"

@interface XJ_AccountBookViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic ,strong) UITableView *myTableView;
@property (nonatomic, strong) ZDXAdditionalView  *additionalView;


/**当前的页数**/
@property(nonatomic,assign)NSInteger currentPage;
/**总共的页数**/
@property(nonatomic,assign)NSInteger totalPage;
@property(nonatomic,assign) NSInteger pageSize;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property(nonatomic,assign) NSInteger dealType;
@end

@implementation XJ_AccountBookViewController
-(NSMutableArray*)dataArray{
    if (!_dataArray) {
        _dataArray =[[NSMutableArray alloc]init];
    }
    return _dataArray;
}
-(ZDXAdditionalView*)additionalView{
    if (!_additionalView) {
        ZDXAdditionalView *additionalView =[ZDXAdditionalView additionalView];
        [KWINDOW addSubview:additionalView];
        UITapGestureRecognizer *myTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapBackgroundView:)];
        [additionalView addGestureRecognizer:myTap];
        _additionalView =additionalView;
    }
    return _additionalView;
}

- (void)didTapBackgroundView:(UITapGestureRecognizer *)sender {
    self.additionalView.hidden =YES;
}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
   
}

-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    /**初始化当前的页数和总共的页数**/
    _currentPage = 1;
    _totalPage =1;
    _pageSize=20;
    _dealType=0;//全部
    ///默认全部
    [self loadDealList];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    
    
}

-(void)creatMainUI{
    
    self.nav_titleLabel.text =@"账本";
    self.nav_backButton.hidden =YES;
    self.nav_rightButton.hidden =NO;
    [self.nav_rightButton setTitle:@"筛选" forState:UIControlStateNormal];
    [self.nav_rightButton addTarget:self action:@selector(Click_navRight) forControlEvents:UIControlEventTouchUpInside];
    
    //添加tableview
    _myTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-SafeAreaTopHeight-kTabBarHeight) style:(UITableViewStylePlain)];
    _myTableView.delegate=self;
    _myTableView.dataSource=self;
    _myTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_myTableView];
    _myTableView.showsHorizontalScrollIndicator =NO;
    _myTableView.showsVerticalScrollIndicator =NO;
    _myTableView.backgroundColor =[UIColor clearColor];
    //    _myTableView.tableHeaderView =self.tableViewHeaderView;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //第二个参数给定下拉刷新触发方法
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshAction)];
    //显示动画(触发selector方法)
    // [header beginRefreshing];
    //显示到tableView
    _myTableView.mj_header = header;
    // 添加上拉刷新
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshAction)];
    _myTableView.mj_footer = footer;
    
    
    self.additionalView.frame =CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.additionalView.hidden =YES;
    self.additionalView.backgroundColor =[UIColor colorWithWhite:0 alpha:0.3];
    self.additionalView.bottomView.clipsToBounds =YES;
    __weak typeof(self) weakSelf =self;
    self.additionalView.block = ^(NSInteger index) {
        
        weakSelf.currentPage = 1;
        weakSelf.totalPage =1;
        weakSelf.dealType =index;
        [weakSelf loadDealList];
        
    };
    
    
}
#pragma mark-上啦刷新 下拉刷新

-(void)headerRefreshAction
{
    NSLog(@"下拉刷新");
    _currentPage = 1;
    _totalPage = 1;
    
    [self loadDealList];
}

-(void)footerRefreshAction
{
    
    NSLog(@"上拉刷新");
    if (_currentPage > _totalPage)
    {
        [MBProgressHUD showError:@"没有更多数据了"];
        [_myTableView.mj_footer endRefreshing];
        [_myTableView.mj_header endRefreshing];
        return;
    }
    [self loadDealList];
    
}
#pragma mark--筛选
-(void)Click_navRight{
    
    self.additionalView.hidden =!self.additionalView.hidden;
    
}

#pragma mark-UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count>0?_dataArray.count:0;
//    return 4;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    XJ_AccountBookListCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        
        cell =[[[NSBundle mainBundle] loadNibNamed:@"XJ_AccountBookListCell" owner:nil options:nil]firstObject];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        cell.backgroundColor =[UIColor clearColor];
    }
    XJ_DealListModel *model =_dataArray[indexPath.row];
    cell.model =model;
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    XJ_DealListModel *model =_dataArray[indexPath.row];
    XJ_AccountBook_DetailViewController *detai =[[XJ_AccountBook_DetailViewController alloc]init];
    detai.dealId =[model.dealId integerValue];
    detai.resultType =[model.resultType integerValue];
    [self.navigationController pushViewController:detai animated:YES];
}

#pragma mark--获取账本列表
-(void)loadDealList{
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:USERID forKey:@"userId"];
    [dic setValue:token forKey:@"token"];
    
    [dic setValue:@(_dealType) forKey:@"dealType"];
    [dic setValue:@(_currentPage) forKey:@"pageNo"];
    [dic setValue:@(20) forKey:@"pageSize"];
    [XJ_Utils signPost:@"/deal/list?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        if (self.currentPage==1) {
            if (self.dataArray.count>0) {
                [self.dataArray removeAllObjects];
            }
        }
        
        NSDictionary * dataDic = [jsonObject objectForKey:@"data"];
        
        NSArray * dealList = [dataDic objectForKey:@"dealList"];
        
        if (dealList.count > 0) {
            
            for (NSDictionary * dic in dealList) {
                
                XJ_DealListModel * model = [XJ_DealListModel mj_objectWithKeyValues:dic];

                [self.dataArray addObject:model];
            }
        }
        [self.myTableView reloadData];
        
        //获取总页数
        if (dataDic[@"totalPage"]!=nil&&![dataDic[@"totalPage"] isKindOfClass:[NSNull class]]) {
            
            self.totalPage = [dataDic[@"totalPage"] integerValue];
        }
        /**数据请求成功之后当前页数+1**/
        self.currentPage++;
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
        
        if (self.currentPage>self.totalPage) {
            
            if (self.myTableView.contentSize.height>self.myTableView.frame.size.height) {
                self.myTableView.mj_footer.state =MJRefreshStateNoMoreData;
                self.myTableView.mj_footer.hidden =YES;
                
                UIView *bottomView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
                bottomView.backgroundColor =ClearColor;
                
                UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(30*PIX, 0, SCREEN_WIDTH-2*30*PIX, 40)];
                label.backgroundColor =ClearColor;
                label.textColor =RGBCOLOR(170, 167, 167);
                label.textAlignment =NSTextAlignmentCenter;
                label.text =@"没有更多数据了";
                label.font =[UIFont systemFontOfSize:15.0];
                [bottomView addSubview:label];
                self.myTableView.tableFooterView =bottomView;
                
                
            }else{
                self.myTableView.mj_footer.state =MJRefreshStateNoMoreData;
                self.myTableView.mj_footer.hidden =NO;
                self.myTableView.tableFooterView =nil;
                
            }
        }else{
            self.myTableView.mj_footer.state =MJRefreshStateIdle;
           self.myTableView.mj_footer.hidden =NO;
            self.myTableView.tableFooterView =nil;
        }
        
        
        
        
    } failure:^(NSInteger recode, NSError *error) {
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
